package cn.wk.controller;

import cn.wk.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/consumer/user")
public class ConsumerController {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @RequestMapping("/{id}")
    private User getUser(@PathVariable Long id){
        //准备url地址 这是写死的地址
        //String url = "http://localhost:4010/provider/user/"+id;
        //通过服务名称获取服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("SPRINGCLOUD-PORVIDER");
        //获取服务
        ServiceInstance instance = instances.get(0);
        //获取url
        URI uri = instance.getUri();
        String url = uri.toString()+"/provider/user/"+id;
        //发起请求
        return restTemplate.getForObject(url,User.class);
    }
}
